package 课堂;

import java.util.Arrays;

/**
 * Created By  醉美柳舞之众星捧月
 *
 * @author song
 * @date 2017/11/10 16:15
 */
public class 二分查找 {
    public static void main(String[] args) {
        int i = 0;
        int[] array = new int[10];
        for (i = 0; i < 10; i++) {
            array[i] = (int) ((Math.random() * 10));
        }
        Arrays.sort(array);
        System.out.println("随机数组为： " + Arrays.toString(array));
        int random = (int) (Math.random() * 10);
        System.out.println("随机数为： " + random);
        System.out.println("二分法查找结果位置为： " + binanySearch(array, random));
    }

    public static int binanySearch(int[] param, int key) {
        int low = 0;
        int high = param.length - 1;
        while (high >= low) {
            int mid = (low + high) / 2;
            if (key < param[mid]) {
                high = mid - 1;
            } else if (key == param[mid]) {
                return mid;
            } else {
                low = mid + 1;
            }
        }
        return 0;
    }
}
